<?php
namespace Admin\Controller;
use Admin\Model\FileModel;
use Common\Model\LogInfoModel;
use Admin\Model\TagModel;
use Admin\Model\ProjectModel;
use Admin\Model\DownlineVersionModel;
use ZipArchive;
use Org\Net\Curl;

/**
 * 系统配置操作
 * 
 * @author xiaoyutab<xiaoyutab@qq.com>
 * @version v1.0.0
 * @copyright (c) 2017, xiaoyutab
 * @adtime 2018-06-01 17:51:50
 */
class SystemController extends BashController{
    /**
     * 系统配置操作
     * 
     * @return void
     * @author xiaoyutab<xiaoyutab@qq.com>
     * @copyright (c) 2017, xiaoyutab
     * @version v1.0.0
     * @adtime 2018-06-01 17:51:50
     */
    public function home_pageAction(){
        // 获取全部的首页tag
        $tag = new TagModel();
        $file = new FileModel();
        if(I('post.')){
            // 如果是post提交过来的值
            $post = I('post.');
            $tag->set_delete_submit_tag();
            // 循环post.name值,判断里面的id并且对应保存或建立连接
            foreach($post['name'] as $id => $name){
                $tag->set_delete_submit('tag', $id);
                if($id > 0){
                    // 保存post提交过来的对应值
                    $tag->where(array('id'=>$id))->save(array(
                        'name' => trim($name),
                        'desc' => $post['desc'][$id],
                        'status' => 99,
                    ));
                }
            }
            // 上传file图片
            $file_list = $this->Upload('file');
            if(is_array($file_list)){
                foreach($file_list as $id => $v){
                    $fid = $file->check_info($v);
                    if($fid){
                        // 删除之前的图片链接
                        $file->get_link()->where(array(
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                            'file_name' => array('EXP','IS NULL'),
                        ))->save(array('status'=>98,'del_time'=>NOW_TIME));
                        // 如果上传成功图片则开始建立封面图连接
                        $file->get_link()->create_info(array(
                            'file_id' => $fid,
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                        ));
                    }
                }
            }
            // 上传icon图片
            $file_list = $this->Upload('icon');
            if(is_array($file_list)){
                foreach($file_list as $id => $v){
                    $fid = $file->check_info($v);
                    if($fid){
                        // 删除之前的图片链接
                        $file->get_link()->where(array(
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                            'file_name' => 'icon',
                        ))->save(array('status'=>98,'del_time'=>NOW_TIME));
                        // 如果上传成功图片则开始建立封面图连接
                        $file->get_link()->create_info(array(
                            'file_id' => $fid,
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                            'file_name' => 'icon',
                        ));
                    }
                }
            }
            // 上传icon选中图片
            $file_list = $this->Upload('icon_on');
            if(is_array($file_list)){
                foreach($file_list as $id => $v){
                    $fid = $file->check_info($v);
                    if($fid){
                        // 删除之前的图片链接
                        $file->get_link()->where(array(
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                            'file_name' => 'icon_on',
                        ))->save(array('status'=>98,'del_time'=>NOW_TIME));
                        // 如果上传成功图片则开始建立封面图连接
                        $file->get_link()->create_info(array(
                            'file_id' => $fid,
                            'target_id' => $id,
                            'target_name' => $file->get_table_id('tag'),
                            'file_name' => 'icon_on',
                        ));
                    }
                }
            }
            return $this->success('修改成功');
            exit;
        }
        $tag->set_delete_reback('tag', $id);
        $this->wget('bootstrap-select2');
        // 重置一下tag标签的删除状态
        $tag->set_delete_reback_tag();
        $list = $tag->where(array('type'=> get_config_id('TagType','首页')))->getList(0,999,FALSE,'`id` ASC');
        if(empty($list)){
            // 如果首页菜单一个也没有的话
            $id = $tag->create_info(array('type'=> get_config_id('TagType','首页')));
            $list = $tag->where(array('type'=> get_config_id('TagType','首页')))->getList(0,999,FALSE,'`id` ASC');
        }
        foreach($list as $k => $v){
            // 循环首页tag，获取其中包含的案例列表和图片列表
            $list[$k]['tar_anli'] = $tag->get_tag_link('tag',$v['id'],'案例');// 获取关联案例
            // 获取首页的图片信息
            $list[$k]['file_img'] = $file->get_img_all('tag',$v['id'],TRUE,NULL);// 取第一张为null的图片
            $list[$k]['icon_img'] = $file->get_img_all('tag',$v['id'],TRUE,'icon');
            $list[$k]['icon_on'] = $file->get_img_all('tag',$v['id'],TRUE,'icon_on');
        }
        $this->assign('home_list',$list);
        $this->assign('project_list_all',$tag->where(array('type'=> get_config_id('TagType', '案例')))->getList(0,999));
        return $this->display();
    }
    
    /**
     * 标记删除状态
     * 
     * @return void
     */
    public function del_imgAction(){
        $tid = intval(I('get.tid'));
        $lid = intval(I('get.lid'));
        $table = trim(I('get.name'));
        if($tid <= 0 || $lid <= 0){
            return $this->error('参数错误');
        }
        $link = (new FileModel())->get_link();
        $table_name = (new LogInfoModel())->get_id($table);
        $info = $link->where(array(
            'id' => $lid,
            'target_id' => $tid,
            'target_name' => $table_name
        ))->find();
        if(empty($info)){
            return $this->error('参数错误');
        }
        if($link->where(array(
                'id' => $lid,
                'target_id' => $tid,
                'target_name' => $table_name
            ))->save(array(
                'status' => 97,
                'del_time' => NOW_TIME
            ))){
            return $this->success('删除成功');
        }
        return $this->error('标记失败'.$lid);
    }
    
    /**
     * 添加首页模块操作
     * 
     * @return void
     * @author xiaoyutab<xiaoyutab@qq.com>
     * @copyright (c) 2017, xiaoyutab
     * @version v1.0.0
     * @adtime 2018-06-16 16:24:36
     */
    public function add_home_pageAction(){
        $tag = new TagModel();
        $id = $tag->create_info(array('type'=> get_config_id('TagType','首页')));
        return $this->ajaxReturn(array('id'=>$id));
    }
    
    /**
     * 删除首页模块操作
     * 
     * @return void
     * @author xiaoyutab<xiaoyutab@qq.com>
     * @copyright (c) 2017, xiaoyutab
     * @version v1.0.0
     * @adtime 2018-06-01 17:51:50
     */
    public function delete_home_pageAction(){
        $tag = new TagModel();
        if($tag->set_delete_status_tag(I('get.id'))){
            return $this->ajaxReturn(array('success'=>TRUE));
        }
        return $this->ajaxReturn(array('success'=>FALSE));
    }
    
    /**
     * 离线数据更新控制
     */
    public function versionAction(){
        $_downline_versionModel = new DownlineVersionModel();
        $line = $_downline_versionModel->order('`ad_time` DESC,`id` DESC')->find();
        if(empty($line)){
            $_downline_versionModel->create_info([]);
            $line = $_downline_versionModel->order('`ad_time` DESC,`id` DESC')->find();
        }
        if(!I('post.')){
            $this->assign('info',$line);
            return $this->display();
        }
        $_file = new FileModel();
        $_zip = new ZipArchive();
        $_curl = new Curl();
        (new \Org\Util\SFile())->rm_dirs(RUNTIME_PATH);// 清空本地缓存【如果未搭建到一处的话请专门请求一下清空缓存的接口】
        $new_data = [];
        $all = FALSE;
        $new_data['desc'] = I('post.desc');
        switch (I('post.version_type')){
            // 修改主版本号
            case 'big':
                $all = TRUE;
                $new_data['big_version'] = $line['big_version'] + 1;
                $new_data['in_version'] = 0;
                $new_data['small_version'] = 0;
                break;
            // 修改发行版本号
            case 'in':
                $all = TRUE;
                $new_data['big_version'] = $line['big_version'];
                $new_data['in_version'] = $line['in_version'] + 1;
                $new_data['small_version'] = 0;
                break;
            // 修改修订版本号
            case 'small':
                $all = TRUE;// 修改每次更新均完全备份更新
                $new_data['big_version'] = $line['big_version'];
                $new_data['in_version'] = $line['in_version'];
                $new_data['small_version'] = $line['small_version'] + 1;
                break;
        }
        $file = C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/'.$line['big_version'].'0.0.zip';
        if(!is_dir(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/')){
            mkdir(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/');
            $all = TRUE;// 第一次创建版本会强制完全备份
        }
        $file = [];
        if($all){
            // 全局打包
            // 获取全部的关联文件信息
            $list = $_file->get_link()->group('file_id')->getList(0,9999);
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['file_id'];
            }
            $list = $_file->where(['id'=>['in',$ids]])->getList(0,9999);
            foreach($list as $v){
                $file[] = $v['file_path'];
            }
        } else {
            // 增量打包
            $list = $_file->get_link()->group('file_id')->getList(0,9999);
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['file_id'];
            }
            // 获取之前的文件包
            $excli = [];
            if(is_file(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/'.$line['big_version'].'.'.$line['in_version'].'.0.zip')){
                $_zip->open(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/'.$line['big_version'].'.'.$line['in_version'].'.0.zip', ZipArchive::CREATE);
                $excli = json_decode(stream_get_contents($_zip->getStream('file_existence.json')), TRUE);
                $_zip->close();
                if(!$excli){
                    $excli = [];
                }
            }
            $list = $_file->where(['id'=>['in',$ids]])->getList(0,9999);
            foreach($list as $v){
                if(!in_array($v['file_path'], $excli)){
                    $file[] = $v['file_path'];
                }
            }
        }
        $_zip->open(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').'/online/'.$new_data['big_version'].'.'.$new_data['in_version'].'.'.$new_data['small_version'].'.zip', ZipArchive::CREATE);
        foreach($file as $v){
            $_zip->addFromString($v,file_get_contents(C('Upload.IMAGE_SAVE_PATH',NULL,'./Public/Upload/').$v));
        }
        // 添加文件保存json
        $_zip->addFromString('file_existence.json', json_encode($file));
        // 获取首页信息并保存起来
        $res_data = [];
        foreach(C('API_DATA.api_list') as $k => $v){
            if(is_numeric($k)){
                $jsons = $_curl->get(C('API_DATA.doman').$v);
                $res_data[$v] = json_decode($jsons,true);
                if(!$res_data[$v] || $res_data[$v]['code'] != 0 || empty($jsons)){
                    $_zip->close();
                    return $this->error('配置错误，请正确配置接口所在域名:API_DATA.doman');
                }
                $_zip->addFromString(str_replace('/','.',$v).'.json', $jsons);
            } else if(is_string($k) && substr($k, 0,1) != '_'){
                foreach(C('API_DATA.api_list._'.$k) as $tv){
                    if(!isset($res_data[$tv])){
                        return $this->error('配置错误:接口 '.$tk.' 配置在了 '.$tv.' 上方');
                    }
//                    foreach($res_data[$tv]['data'] as $ttk => $ttv){
//                        if($ttk != $k && is_array($ttv)){
//                            foreach($ttv as $tttk => $tttv){
//                                if($tttk.'' == $k.''){
//                                    $jsons = $_curl->post(C('API_DATA.doman').$v, [$k => $tttv]);
//                                    $_zip->addFromString(str_replace('/','.',$v).'_'.$tttv.'.json', $jsons);
//                                } else if(isset ($tttv[$k]) && is_string($tttv[$k])){
//                                    $jsons = $_curl->post(C('API_DATA.doman').$v, [$k => $tttv[$k]]);
//                                    $_zip->addFromString(str_replace('/','.',$v).'_'.$tttv[$k].'.json', $jsons);
//                                }
//                            }
//                        }
//                    }
                }
            } else {
                continue;
            }
        }
        $_tag = new TagModel();
        $_project = new ProjectModel();
        $_file = new FileModel();
        $project_list = $_project->where(['status'=>99])->field(['id','name','price','wl_no','content','ad_time'])->select();
        foreach($project_list as $k => $v){
            $project_list[$k]['ad_time'] = date('Y-m-d H:i:s',$v['ad_time']);
            $temp = $_file->get_img_all('project', $v['id']);
            foreach($temp as $tv){
                $project_list[$k]['file_path'][] = $tv['file_content']['file_path'];
            }
            $project_list[$k]['file_path'] = implode(',', $project_list[$k]['file_path']);
        }
        $_zip->addFromString('project_list.json', json_encode($project_list));
        $_zip->addFromString('project_link.json', json_encode($_tag->get_link()->where([
            'target_name' => $_tag->get_table_id('project'),
            'file_id' => ['gt',0],
            'target_id' => ['gt',0],
        ])->field([
            'file_id' => 'parentid',
            'target_id' => 'goodsid',
        ])->group('parentid,goodsid')->select()));
        $_zip->addFromString('tags_link.json', json_encode($_tag->get_link()->where([
            'target_name' => $_tag->get_table_id('tag'),
            'file_id' => ['gt',0],
            'target_id' => ['gt',0],
        ])->field([
            'file_id' => 'parentid',
            'target_id' => 'goodsid',
        ])->group('parentid,goodsid')->select()));
        $_zip->close();
        $new_data['file_url'] = '/online/'.$new_data['big_version'].'.'.$new_data['in_version'].'.'.$new_data['small_version'].'.zip';
        $_downline_versionModel->create_info($new_data);
//        if($_downline_versionModel->create_info($new_data)){
            return $this->success('版本更新成功');
//        }
//        return $this->error('系统错误');
    }
}